import store from '../store'
import * as types from '../store/action-types'

const loginPermission = async function(to, from, next) {
  console.log(to);
  
  let r = await store.dispatch(`user/${types.USER_VALIDATE}`);
  let needLogin = to.matched.some(item => item.meta.needLogin);
  console.log(needLogin);
  console.log(r);
  
  console.log(store.state.user.hasPermission);
  
  if (!store.state.user.hasPermission) {
    if (needLogin) {
       if (r) {
            next(); // 需要登录 并且登录过了 继续即可
        } else {
            next('/login');//需要登录 且没有登陆就返回登录页进行登录
        }
    } else {
      if (to.path === '/login') {
            next('/');
        } else {//登录过没有访问登录页面想干什么就干什么
            next();
        }
    }
  }
  next();
}

export const menuPermission = async function(to, from, next) {
  if (store.state.user.hasPermission) {
    // 添加路由这里需要判断是否添加过路由了 
    if (!store.state.user.menuPermission) {
        // 添加路由完成，但是是属于异步加载，不会立即更新
        store.dispatch(`user/${types.ADD_ROUTE}`);
       //replace 相当于replaceState替换掉并不进入历史记录 把路径添加完全
        next({ ...to, replace: true }); // 如果是next()时，进入到页面时报404.
    } else {
        next();
    }
} else {
    next();
}
}

export const createWebSocket = async function (to, from, next) {
  if (store.state.user.hasPermission && !store.state.ws) {
    store.dispatch(`${types.CREATE_WEBSOCKET}`)
    next()
  } else {
    next()
  }
}
export default {
  loginPermission,
  menuPermission,
  createWebSocket
}